import time
from machine import Pin

# Return distance (cm). 
def measureDist():
    trigPin.on()
    time.sleep_us(15)
    trigPin.off()

    t0 = time.ticks_us()
    # wait for 1
    while not echoPin.value():
        if  time.ticks_diff(time.ticks_us(), t0)>5000:  # 5s
            # print("Check Pin.")
            return 0

    t1= time.ticks_us()  # time of rising edge
    # wait for 0
    while echoPin.value():
        # limit measure distance 0.5m. 1/314=2.941ms 
        if  time.ticks_diff(time.ticks_us(), t1)>2941:
            # print("Out of range.")
            return 50
    delta = time.ticks_diff(time.ticks_us(), t1) # us
    return int(delta*0.017) #cm

# distance sensor
trigPin = Pin(5, Pin.OUT) #GPIO5 D1
echoPin = Pin(4, Pin.IN)  #GPIO4 D2

while True:
    distance = measureDist()
    print("distance: ", distance)
    time.sleep_ms(100)